package com.dove.ohpm.ui

import com.dove.ohpm.model.PackageFile
import com.dove.ohpm.service.NetClient
import com.dove.ohpm.service.ProjectLoader
import com.dove.ohpm.service.UISettingConfigState
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowFactory
import com.intellij.ui.content.ContentFactory
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.util.regex.Pattern
import javax.swing.JComponent

class UISidebar: ToolWindowFactory {
    private var page = 1
    private val form = view()
    private var searchKeywords = ""
    private val client = NetClient()
    private var packageFile: PackageFile? = null
    private val component: JComponent = form.mainPanel

    init {
        form.searchButton.addActionListener { search() }
        form.comboBox1.addItemListener {
            try {
                val key = it.item.toString()
                val dependence = ProjectLoader.getDependence(key).dependencies
                if (dependence != null)
                    form.dependencies(dependence)
            } catch (ex: Exception) {
                Messages.showErrorDialog(null as Project?, ex.message, "Error")
            }
        }
        form.nextButton.addActionListener {
            try {
                if (searchKeywords.isNotEmpty()) {
                    page += 1
                    val list = client.search(form.cbCustom.isSelected, searchKeywords, page)
                    if (list.isNotEmpty()) {
                        list.forEach {
                            val ver = packageFile?.dependencies?.get(it.name)
                            val keywords = it.keywords?.joinToString(", ")
                            form.addChild(
                                it.name,
                                it.authorName,
                                it.description,
                                it.latestVersion,
                                keywords,
                                ver,
                                it.id
                            )
                        }
                    }
                }
            } catch (ex: Exception) {
                Messages.showErrorDialog(null as Project?, ex.message, "Error")
            }
        }
        form.textField.addKeyListener(object : KeyAdapter() {
            override fun keyPressed(e: KeyEvent) {
                if (e.keyChar.code == KeyEvent.VK_ENTER)
                    search()
            }
        })
        form.cbCustom.addActionListener {
            if (form.cbCustom.isSelected) {
                val state = ApplicationManager.getApplication()
                    .getService(
                        UISettingConfigState::class.java
                    )
                val hostPort = state.hostPort
                val ipOrDomainRegex =
                    "^((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)){3}|((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6})$"
                val pattern = Pattern.compile(ipOrDomainRegex)
                form.lbMessage.setText("")
                if (hostPort <= 0 || hostPort > 65535 || !pattern.matcher(state.hostUrl).matches()) {
                    form.cbCustom.setSelected(false)
                    form.lbMessage.setText("请输入正确的配置！")
                }
            }
        }
    }

    private fun search() {
        try {
            searchKeywords = form.textField.text
            form.clearChild()
            if (searchKeywords.isNotEmpty()) {
                page = 1
                val list = client.search(form.cbCustom.isSelected, searchKeywords, page)
                if (list.isNotEmpty()) {
                    list.forEach {
                        val ver = packageFile?.dependencies?.get(it.name)
                        val keywords = it.keywords?.joinToString(", ")
                        form.addChild(
                            it.name,
                            it.authorName,
                            it.description,
                            it.latestVersion,
                            keywords,
                            ver,
                            it.id
                        )
                    }
                }
            }
        } catch (ex: Exception) {
            Messages.showErrorDialog(null as Project?, ex.message, "Error")
        }
    }

    override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) {
        try {
            ProjectLoader.getPackages(project)
            toolWindow.contentManager.addContent(ContentFactory.getInstance().createContent(component, "", false))
            val names: MutableList<String> = mutableListOf()
            ProjectLoader.packages.forEach { names.add(it.key) }
            form.addPackages(names)
        } catch (ex: Exception) {
            Messages.showErrorDialog(null as Project?, ex.message, "Error")
        }
    }
}